package util.android;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class ViewUtil {
	
	/* layoutID: Debe ser de la forma R.layout.milayout
	 */
	public View inflar(Context context, int layoutID) {
		return View.inflate(context, layoutID, null);
	}
	
	public static void ocultarTeclado(EditText editText) {
		Context context =  editText.getContext();
		InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

	public static void aparecerTeclado(EditText editText) {
		Context context =  editText.getContext();
		InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editText,InputMethodManager.SHOW_FORCED);
	}
	
	public static String getAttributo(String nombre, AttributeSet attrs) {
		int n = attrs.getAttributeCount();
		for(int i=0; i<n; i++) {
			if(attrs.getAttributeName(i).equals(nombre))
				return attrs.getAttributeValue(i);
		}	
		return null;
	}
	
	public static boolean existeAttributo(String nombre, AttributeSet attrs) {
		int n = attrs.getAttributeCount();
		for(int i=0; i<n; i++) {
			String a = attrs.getAttributeName(i); 
			if(a!=null && a.equals(nombre))
				return true;
		}	
		return false;
	}

	//SmartViewPager
	//https://bitbucket.org/NxAlex/swipes-navigation-demo/src/4db50c3253637185f9b3610fff6f1a9401fd25eb/sample/SwipeNavigationDemo/src/com/visionapps/demo/swipe/view/SmartViewPager.java?at=master
	
	//ViewPager inside a ScrollView does not scroll correclty
	//http://stackoverflow.com/questions/8381697/viewpager-inside-a-scrollview-does-not-scroll-correclty
	
	
	public static void setTextView(Activity activity, int textViewId, String texto) {
		TextView tv = (TextView) activity.findViewById(textViewId);
		tv.setText(texto);
	}

	public static void setTextView(Dialog dialog, int textViewId, String texto) {
		TextView tv = (TextView) dialog.findViewById(textViewId);
		tv.setText(texto);
	}
	
	//NOTA: Solo funciona cuando los hijos directos de RadioGroup son RadioButtons
	public static RadioButton getRadioButtonSeleccionado(RadioGroup rg) {
		int radioButtonID = rg.getCheckedRadioButtonId();
		return (RadioButton) rg.findViewById(radioButtonID);
	}
	
	//http://stackoverflow.com/questions/6440259/how-to-get-the-selected-index-of-a-radiogroup-in-android
	public static int getIndiceSeleccionado(RadioGroup rg) {
		View radioButton = getRadioButtonSeleccionado(rg);
		int idx = rg.indexOfChild(radioButton);
		return idx;
	}

	//http://stackoverflow.com/questions/9175635/how-to-set-radio-button-checked-as-default-in-radiogroup-with-android	
	public static void setChecked(RadioGroup rg, int idRadioButton) {
		//Otra forma:
		rg.check(idRadioButton);
	}
	
	public static boolean childrenInstanceOf(View view, Class<?> claseHijo) {
		if(claseHijo.isInstance(view))
			return true;
		
		if(view instanceof ViewGroup) {
			ViewGroup viewGroup = (ViewGroup)view;
			for (int i = 0; i < viewGroup.getChildCount(); i++) {        
		        View child = viewGroup.getChildAt(i);
		        if(childrenInstanceOf(child,claseHijo)) {
		        	return true;
		        }
		    }
		}		
		return false;
	}
	
	public static List<View> getAllChildren(ViewGroup viewGroup) {
		return getAllChildren(viewGroup,null);
	}
	
	//http://stackoverflow.com/questions/18668897/android-get-all-children-elements-of-a-viewgroup
	@SuppressWarnings("unchecked")
	public static <C extends View> List<C> getAllChildren(ViewGroup viewGroup, Class<C> claseFiltro) {
	    List<C> lista = new ArrayList<C>();
	    for (int i = 0; i < viewGroup.getChildCount(); i++) {
	        List<C> sublista = new ArrayList<C>();
	        //sublista.add(viewGroup);
	        
	        View child = viewGroup.getChildAt(i);
	        if(claseFiltro==null || claseFiltro.isInstance(child))
	        	sublista.add((C)child);
	        
	        if(child instanceof ViewGroup) {
	        	sublista.addAll(getAllChildren((ViewGroup)child, claseFiltro));
	        }
	        
	        lista.addAll(sublista);
	    }
	    return lista;
	}
	
	public static List<View> getAllChildren(ViewGroup viewGroup, int nivel) {
		List<View> lista = new ArrayList<View>();
		for (int i = 0; i < viewGroup.getChildCount(); i++) {        
			List<View> sublista = new ArrayList<View>();
			//sublista.add(viewGroup);
			
			View child = viewGroup.getChildAt(i);
			sublista.add(child);
			
			if(nivel>1 && child instanceof ViewGroup) {
				sublista.addAll(getAllChildren((ViewGroup)child,nivel--));
			}			
			lista.addAll(sublista);
		}
		return lista;
	}
	
	public static void onClick(View v, int idBtn, View.OnClickListener listener) {
		View btn = v.findViewById(idBtn);
		btn.setOnClickListener(listener);
	}
	
	public static void onClick(Activity activity, int idBtn, View.OnClickListener listener) {
		View btn = activity.findViewById(idBtn);
		btn.setOnClickListener(listener);
	}
	
	/**
	 * Usado para agregar hijos que han sido creados con inflate
	 * @param padre
	 * @param hijo
	 */
	public static void addViewMatch_Wrap(ViewGroup padre, View hijo) {
		LinearLayout.LayoutParams params = new LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 
				LinearLayout.LayoutParams.WRAP_CONTENT
		);
		padre.addView(hijo, params);
	}
	
	public static void addViewMatch_Match(ViewGroup padre, View hijo) {
		LinearLayout.LayoutParams params = new LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 
				LinearLayout.LayoutParams.MATCH_PARENT
				);
		padre.addView(hijo, params);
	}
	
	public static void addViewWrap_Wrap(ViewGroup padre, View hijo) {
		LinearLayout.LayoutParams params = new LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, 
				LinearLayout.LayoutParams.WRAP_CONTENT
		);
		padre.addView(hijo, params);
	}
	
}
